﻿using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.NIP_WorkFlow;
using NP.BPMReportPlatform.RecurringJobs.Dto.OldBPMSyncUser;
using NP.BPMReportPlatform.RecurringJobs.Dtos;
using NP.BPMReportPlatform.Utilities;
using Serilog;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace NP.BPMReportPlatform.RecurringJobs
{
    public class OldBPMSyncUserJob : BpmReportPlatformRecurringJob, IOldBPMSyncUserJob
    {
        private readonly SqlSugarClient _dbNIPWorkFlow;

        private readonly ILogger _logger;

        public OldBPMSyncUserJob(
            ISqlSugarAppService sqlSugarAppService,
            ILogger logger)
        {
            _dbNIPWorkFlow = sqlSugarAppService.GetNIPWolkFlowInstance();
            _logger = logger;
        }

        /// <summary>
        /// 同步人员
        /// </summary>
        /// <returns></returns>
        public async Task SyncUser()
        {
            try
            {
                await DoWork();
            }            
            catch(Exception ex)
            {
                _logger.Error("OldBPMSyncUserJob.SyncUser Error:" + ex.Message);
            }
        }

        private async Task DoWork()
        {
            var watch = new Stopwatch();
            watch.Start();

            var nipUserInfo = await this.GetNIPVUserInfo();//从立邦获取用户数据
            var nipOrgRelations = await this.GetNIPOrgRelation();//从立邦获取组织结构数据

            await SyncAllSite();//同步省市数据
            await SyncMdsHrOrganization(nipOrgRelations);//同步hr组织数据
            await SyncMDSHrObjRelation(nipOrgRelations);//同步对象关系表A002数据
            await SyncPCUSERT(nipUserInfo);//同步Sync_PC_USER_T用户表数据，全量同步，包括离职数据

            //查询所有hr人员表数据
            var hrPersons = await _dbNIPWorkFlow.Queryable<MDS_Hr_Person>().OrderBy(x => x.ID, OrderByType.Desc).ToListAsync();
            var iHrPersonList = new List<MDS_Hr_Person>();
            var uHrPersonList = new List<MDS_Hr_Person>();
            //查询所有hr岗位数据
            var hrPosts = await _dbNIPWorkFlow.Queryable<MDS_Hr_Post>().OrderBy(x => x.ID, OrderByType.Desc).ToListAsync();
            var iHrPostList = new List<MDS_Hr_Post>();
            var uHrPostList = new List<MDS_Hr_Post>();
            //查询所有用户数据
            var users = await _dbNIPWorkFlow.Queryable<MDS_User>().OrderBy("timestamp desc").ToListAsync();
            var iUserList = new List<MDS_User>();
            var uUserList = new List<MDS_User>();
            //查询所有用户组织关系数据
            var userOrgs = await _dbNIPWorkFlow.Queryable<MDS_Hr_UserOrgRelation>().ToListAsync();
            var iUserOrgList = new List<MDS_Hr_UserOrgRelation>();
            var uUserOrgList = new List<MDS_Hr_UserOrgRelation>();
            //查询所有对象关系数据
            var objRelations = await _dbNIPWorkFlow.Queryable<MDS_Hr_ObjRelation>().OrderBy(x => x.ID, OrderByType.Desc).ToListAsync();
            var iObjRelationList = new List<MDS_Hr_ObjRelation>();
            var uObjRelationList = new List<MDS_Hr_ObjRelation>();

            //删除人员和上级人员关系表数据
            var userBossIsDel = await _dbNIPWorkFlow.Deleteable<NIP_Sync_UserBossRelation>().ExecuteCommandAsync() > 0 ||
                !await _dbNIPWorkFlow.Queryable<NIP_Sync_UserBossRelation>().AnyAsync();
            var iUserBossRelation = new List<NIP_Sync_UserBossRelation>();

            var userBossData = nipUserInfo.Where(x => x.Status.Equals("3")).ToList();//在职数据

            foreach (var userData in userBossData)
            {
                // 更新MDS_Hr_Person 7开头的人员编号，是手动添加数据不更新
                if (!userData.SapEmployeeId.IsNullOrEmpty())
                {
                    var hrPerson = hrPersons.Where(x => !x.PersonNo.IsNullOrEmpty()).FirstOrDefault(x => x.PersonNo.Trim().Equals(userData.SapEmployeeId));
                    if (hrPerson == null) //新增数据
                    {
                        var ihrPerson = new MDS_Hr_Person
                        {
                            PersonNo = userData.SapEmployeeId,
                            Name = userData.Name ?? "",
                            AccountName = userData.LoginName ?? "",
                            EnglishName = userData.LoginName ?? "",
                            Mail = userData.Email ?? "",
                            UserID = userData.LoginName ?? "",
                            InCompanyID = userData.SapCompanyCode,
                            Province = userData.Province,
                            CityName = userData.cityname,
                            ABKRS = userData.ABKRS,
                            SyncTime = DateTime.Now
                        };
                        if (!iHrPersonList.Any(x => x.PersonNo.Equals(ihrPerson.PersonNo)))
                        {
                            iHrPersonList.Add(ihrPerson);
                        }
                    }
                    else if (hrPerson.Name != userData.Name || hrPerson.AccountName != userData.LoginName ||
                        hrPerson.EnglishName != userData.LoginName || hrPerson.Mail != userData.Email ||
                        hrPerson.UserID != userData.LoginName || hrPerson.InCompanyID != userData.SapCompanyCode ||
                        hrPerson.Province != userData.Province || hrPerson.CityName != userData.cityname ||
                        hrPerson.ABKRS != userData.ABKRS)
                    {
                        hrPerson.Name = userData.Name ?? "";
                        hrPerson.AccountName = userData.LoginName ?? "";
                        hrPerson.EnglishName = userData.LoginName ?? "";
                        hrPerson.Mail = userData.Email ?? "";
                        hrPerson.UserID = userData.LoginName ?? "";
                        hrPerson.InCompanyID = userData.SapCompanyCode;
                        hrPerson.Province = userData.Province;
                        hrPerson.CityName = userData.cityname;
                        hrPerson.ABKRS = userData.ABKRS;
                        hrPerson.SyncTime = DateTime.Now;
                        uHrPersonList.Add(hrPerson);
                    }
                }

                // 更新MDS_Hr_Post
                if (!userData.EmployeePost.IsNullOrEmpty())
                {
                    var hrPost = hrPosts.Where(x => !x.ObjID.IsNullOrEmpty()).FirstOrDefault(x => x.ObjID.Trim().Equals(userData.EmployeePost));
                    if (hrPost == null)
                    {
                        var ihrPost = new MDS_Hr_Post
                        {
                            ObjID = userData.EmployeePost,
                            ObjName = userData.EmployeePostName ?? "",
                            ObjType = "S"
                        };
                        if (!iHrPostList.Any(x => x.ObjID.Equals(ihrPost.ObjID)))
                        {
                            iHrPostList.Add(ihrPost);
                        }                        
                    }
                    else if(hrPost.ObjName != userData.EmployeePostName)
                    {
                        hrPost.ObjName = userData.EmployeePostName ?? "";
                        uHrPostList.Add(hrPost);
                    }
                }

                // 更新MDS_User 7开头的人员编号，是手动添加数据不更新
                if (!userData.SapEmployeeId.IsNullOrEmpty())
                {
                    var user = users.Where(x => !x.EmployeeNo.IsNullOrEmpty()).FirstOrDefault(x => x.EmployeeNo.Trim().Equals(userData.SapEmployeeId));
                    if (user == null)
                    {
                        var iuser = new MDS_User
                        {
                            ID = Guid.NewGuid(),
                            AccountName = userData.LoginName ?? "",
                            EmployeeNo = userData.SapEmployeeId,
                            Name = userData.Name ?? "",
                            DisplayName = userData.Name ?? "",
                            Mail = userData.Email ?? "",
                            Deleted = false,
                            SyncTime = DateTime.Now
                        };
                        if (!iUserList.Any(x => x.EmployeeNo.Equals(iuser.EmployeeNo)))
                        {
                            iUserList.Add(iuser);
                        }
                    }
                    else if (user.AccountName != userData.LoginName || user.Name != userData.Name ||
                        user.DisplayName != userData.Name || user.Mail != userData.Email || user.Deleted == true)
                    {
                        user.AccountName = userData.LoginName ?? "";
                        user.Name = userData.Name ?? "";
                        user.DisplayName = userData.Name ?? "";
                        user.Mail = userData.Email ?? "";
                        user.Deleted = false;
                        user.SyncTime = DateTime.Now;
                        uUserList.Add(user);
                    }
                }

                // 更新MDS_Hr_UserOrgRelation
                if (!userData.OBJID_1.IsNullOrEmpty())
                {
                    var userOrg = userOrgs.Where(x => !x.EmployeeID.IsNullOrEmpty()).FirstOrDefault(x => x.EmployeeID.Trim().Equals(userData.SapEmployeeId));
                    var org1 = nipOrgRelations.FirstOrDefault(x => x.OBJID == userData.OBJID_1);
                    if (nipOrgRelations.FirstOrDefault(x => x.OBJID == userData.OBJID_1) != null)
                    {
                        var org2 = nipOrgRelations.FirstOrDefault(x => x.OBJID == userData.OBJID_2);
                        var org3 = nipOrgRelations.FirstOrDefault(x => x.OBJID == userData.OBJID_3);
                        var org4 = nipOrgRelations.FirstOrDefault(x => x.OBJID == userData.OBJID_4);
                        var org5 = nipOrgRelations.FirstOrDefault(x => x.OBJID == userData.OBJID_5);
                        var org6 = nipOrgRelations.FirstOrDefault(x => x.OBJID == userData.OBJID_6);
                        var org7 = nipOrgRelations.FirstOrDefault(x => x.OBJID == userData.OBJID_7);
                        var org8 = nipOrgRelations.FirstOrDefault(x => x.OBJID == userData.OBJID_8);
                        var org9 = nipOrgRelations.FirstOrDefault(x => x.OBJID == userData.OBJID_9);
                        if (userOrg == null)
                        {
                            var iUserOrg = new MDS_Hr_UserOrgRelation
                            {
                                EmployeeID = userData.SapEmployeeId,
                                EmployeeName = userData.Name,
                                SOBID1 = org1.SOBID,
                                STEXT1 = org1.STEXT,
                                OBJID1 = org1.OBJID.ObjToNullInt(),
                                SHORT1 = org1.SHORT,
                                SOBID2 = org2?.SOBID,
                                STEXT2 = org2?.STEXT,
                                OBJID2 = org2?.OBJID.ObjToNullInt(),
                                SHORT2 = org2?.SHORT,
                                SOBID3 = org3?.SOBID,
                                STEXT3 = org3?.STEXT,
                                OBJID3 = org3?.OBJID.ObjToNullInt(),
                                SHORT3 = org3?.SHORT,
                                SOBID4 = org4?.SOBID,
                                STEXT4 = org4?.STEXT,
                                OBJID4 = org4?.OBJID.ObjToNullInt(),
                                SHORT4 = org4?.SHORT,
                                SOBID5 = org5?.SOBID,
                                STEXT5 = org5?.STEXT,
                                OBJID5 = org5?.OBJID.ObjToNullInt(),
                                SHORT5 = org5?.SHORT,
                                SOBID6 = org6?.SOBID,
                                STEXT6 = org6?.STEXT,
                                OBJID6 = org6?.OBJID.ObjToNullInt(),
                                SHORT6 = org7?.SHORT,
                                SOBID7 = org7?.SOBID,
                                STEXT7 = org7?.STEXT,
                                OBJID7 = org7?.OBJID.ObjToNullInt(),
                                SHORT7 = org7?.SHORT,
                                SOBID8 = org8?.SOBID,
                                STEXT8 = org8?.STEXT,
                                OBJID8 = org8?.OBJID.ObjToNullInt(),
                                SHORT8 = org8?.SHORT,
                                SOBID9 = org9?.SOBID,
                                STEXT9 = org9?.STEXT,
                                OBJID9 = org9?.OBJID.ObjToNullInt(),
                                SHORT9 = org9?.SHORT,
                            };
                            if (!iUserOrgList.Any(x => x.EmployeeID.Equals(iUserOrg.EmployeeID)))
                            {
                                iUserOrgList.Add(iUserOrg);
                            }                            
                        }
                        else if (
                            userOrg.EmployeeName != userData.Name||
                            userOrg.SOBID1 != org1.SOBID||
                            userOrg.STEXT1 != org1.STEXT||
                            userOrg.OBJID1 != org1.OBJID.ObjToNullInt() ||
                            userOrg.SHORT1 != org1.SHORT||
                            userOrg.SOBID2 != org2?.SOBID||
                            userOrg.STEXT2 != org2?.STEXT||
                            userOrg.OBJID2 != org2?.OBJID.ObjToNullInt()||
                            userOrg.SHORT2 != org2?.SHORT||
                            userOrg.SOBID3 != org3?.SOBID||
                            userOrg.STEXT3 != org3?.STEXT||
                            userOrg.OBJID3 != org3?.OBJID.ObjToNullInt()||
                            userOrg.SHORT3 != org3?.SHORT||
                            userOrg.SOBID4 != org4?.SOBID||
                            userOrg.STEXT4 != org4?.STEXT||
                            userOrg.OBJID4 != org4?.OBJID.ObjToNullInt()||
                            userOrg.SHORT4 != org4?.SHORT||
                            userOrg.SOBID5 != org5?.SOBID||
                            userOrg.STEXT5 != org5?.STEXT||
                            userOrg.OBJID5 != org5?.OBJID.ObjToNullInt()||
                            userOrg.SHORT5 != org5?.SHORT||
                            userOrg.SOBID6 != org6?.SOBID||
                            userOrg.STEXT6 != org6?.STEXT||
                            userOrg.OBJID6 != org6?.OBJID.ObjToNullInt()||
                            userOrg.SHORT6 != org7?.SHORT||
                            userOrg.SOBID7 != org7?.SOBID||
                            userOrg.STEXT7 != org7?.STEXT||
                            userOrg.OBJID7 != org7?.OBJID.ObjToNullInt()||
                            userOrg.SHORT7 != org7?.SHORT||
                            userOrg.SOBID8 != org8?.SOBID||
                            userOrg.STEXT8 != org8?.STEXT||
                            userOrg.OBJID8 != org8?.OBJID.ObjToNullInt()||
                            userOrg.SHORT8 != org8?.SHORT||
                            userOrg.SOBID9 != org9?.SOBID||
                            userOrg.STEXT9 != org9?.STEXT||
                            userOrg.OBJID9 != org9?.OBJID.ObjToNullInt()||
                            userOrg.SHORT9 != org9?.SHORT)
                        {
                            userOrg.EmployeeName = userData.Name;
                            userOrg.SOBID1 = org1.SOBID;
                            userOrg.STEXT1 = org1.STEXT;
                            userOrg.OBJID1 = org1.OBJID.ObjToNullInt();
                            userOrg.SHORT1 = org1.SHORT;
                            userOrg.SOBID2 = org2?.SOBID;
                            userOrg.STEXT2 = org2?.STEXT;
                            userOrg.OBJID2 = org2?.OBJID.ObjToNullInt();
                            userOrg.SHORT2 = org2?.SHORT;
                            userOrg.SOBID3 = org3?.SOBID;
                            userOrg.STEXT3 = org3?.STEXT;
                            userOrg.OBJID3 = org3?.OBJID.ObjToNullInt();
                            userOrg.SHORT3 = org3?.SHORT;
                            userOrg.SOBID4 = org4?.SOBID;
                            userOrg.STEXT4 = org4?.STEXT;
                            userOrg.OBJID4 = org4?.OBJID.ObjToNullInt();
                            userOrg.SHORT4 = org4?.SHORT;
                            userOrg.SOBID5 = org5?.SOBID;
                            userOrg.STEXT5 = org5?.STEXT;
                            userOrg.OBJID5 = org5?.OBJID.ObjToNullInt();
                            userOrg.SHORT5 = org5?.SHORT;
                            userOrg.SOBID6 = org6?.SOBID;
                            userOrg.STEXT6 = org6?.STEXT;
                            userOrg.OBJID6 = org6?.OBJID.ObjToNullInt();
                            userOrg.SHORT6 = org7?.SHORT;
                            userOrg.SOBID7 = org7?.SOBID;
                            userOrg.STEXT7 = org7?.STEXT;
                            userOrg.OBJID7 = org7?.OBJID.ObjToNullInt();
                            userOrg.SHORT7 = org7?.SHORT;
                            userOrg.SOBID8 = org8?.SOBID;
                            userOrg.STEXT8 = org8?.STEXT;
                            userOrg.OBJID8 = org8?.OBJID.ObjToNullInt();
                            userOrg.SHORT8 = org8?.SHORT;
                            userOrg.SOBID9 = org9?.SOBID;
                            userOrg.STEXT9 = org9?.STEXT;
                            userOrg.OBJID9 = org9?.OBJID.ObjToNullInt();
                            userOrg.SHORT9 = org9?.SHORT;
                            uUserOrgList.Add(userOrg);
                        }
                    }
                }

                //从源数据获取直接上级人员数据
                var boss = userBossData.Where(x => !x.SapEmployeeId.IsNullOrEmpty()).FirstOrDefault(x => x.SapEmployeeId.Equals(userData.BossEmployeeId));
                // 更新MDS_Hr_ObjRelation
                if (!userData.EmployeePost.IsNullOrEmpty())
                {
                    // A002直接上级                    
                    if (boss != null && !boss.EmployeePost.IsNullOrEmpty())
                    {
                        var objRelation1 = objRelations.FirstOrDefault(
                            x => !x.ObjType1.IsNullOrEmpty() && !x.RelationType.IsNullOrEmpty() && !x.ObjID1.IsNullOrEmpty() &&
                            x.ObjType1.Equals("S") && x.RelationType.Equals("A002") && x.ObjID1.Equals(userData.EmployeePost));
                        if (objRelation1 == null)
                        {
                            var ihrObjRelation1 = new MDS_Hr_ObjRelation
                            {
                                ObjType1 = "S",
                                ObjID1 = userData.EmployeePost,
                                ObjName1 = userData.EmployeePostName ?? "",
                                RelationType = "A002",
                                ObjType2 = "S",
                                ObjID2 = boss.EmployeePost,
                                ObjName2 = boss.EmployeePostName ?? "",
                                SyncTime = DateTime.Now
                            };
                            if (!iObjRelationList.Any(x =>
                                x.ObjType1.Equals("S") && x.RelationType.Equals("A002") && x.ObjID1.Equals(userData.EmployeePost)))
                            {
                                iObjRelationList.Add(ihrObjRelation1);
                            }
                        }
                        else if (objRelation1.ObjType2 != "S" ||
                            objRelation1.ObjID2 != boss.EmployeePost ||
                            objRelation1.ObjName2 != boss.EmployeePostName)
                        {
                            objRelation1.ObjType2 = "S";
                            objRelation1.ObjID2 = boss.EmployeePost;
                            objRelation1.ObjName2 = boss.EmployeePostName ?? "";
                            objRelation1.SyncTime = DateTime.Now;
                            uObjRelationList.Add(objRelation1);
                        }
                    }
                    // A003组织和岗位关系                    
                    if (!userData.Org.IsNullOrEmpty())
                    {
                        var objRelation2 = objRelations.FirstOrDefault(
                            x => !x.ObjType1.IsNullOrEmpty() && !x.RelationType.IsNullOrEmpty() && !x.ObjID1.IsNullOrEmpty() &&
                            x.ObjType1.Equals("S") && x.RelationType.Equals("A003") && x.ObjID1.Equals(userData.EmployeePost));
                        if (objRelation2 == null)
                        {
                            var ihrObjRelation2 = new MDS_Hr_ObjRelation
                            {
                                ObjType1 = "S",
                                ObjID1 = userData.EmployeePost,
                                ObjName1 = userData.EmployeePostName ?? "",
                                RelationType = "A003",
                                ObjType2 = "O",
                                ObjID2 = userData.Org,
                                ObjName2 = userData.OrgName ?? "",
                                SyncTime = DateTime.Now
                            };
                            if (!iObjRelationList.Any(x =>
                                x.ObjType1.Equals("S") && x.RelationType.Equals("A003") && x.ObjID1.Equals(userData.EmployeePost)))
                            {
                                iObjRelationList.Add(ihrObjRelation2);
                            }
                        }
                        else if (objRelation2.ObjType2 != "O" ||
                            objRelation2.ObjID2 != userData.Org ||
                            objRelation2.ObjName2 != userData.OrgName)
                        {
                            objRelation2.ObjType2 = "O";
                            objRelation2.ObjID2 = userData.Org;
                            objRelation2.ObjName2 = userData.OrgName ?? "";
                            objRelation2.SyncTime = DateTime.Now;
                            uObjRelationList.Add(objRelation2);
                        }
                    }
                    // A008岗位和人员关系                    
                    if (!userData.SapEmployeeId.IsNullOrEmpty())
                    {
                        var objRelation3 = objRelations.FirstOrDefault(
                            x => !x.ObjType2.IsNullOrEmpty() && !x.RelationType.IsNullOrEmpty() && !x.ObjID2.IsNullOrEmpty() &&
                            x.ObjType2.Equals("P") && x.RelationType.Equals("A008") && x.ObjID2.Equals(userData.SapEmployeeId));
                        if (objRelation3 == null)
                        {
                            var ihrObjRelation3 = new MDS_Hr_ObjRelation
                            {
                                ObjType1 = "S",
                                ObjID1 = userData.EmployeePost,
                                ObjName1 = userData.EmployeePostName ?? "",
                                RelationType = "A008",
                                ObjType2 = "P",
                                ObjID2 = userData.SapEmployeeId,
                                ObjName2 = userData.Name,
                                SyncTime = DateTime.Now
                            };
                            if (!iObjRelationList.Any(x =>
                               x.ObjType2.Equals("P") && x.RelationType.Equals("A008") && x.ObjID2.Equals(userData.SapEmployeeId)))
                            {
                                iObjRelationList.Add(ihrObjRelation3);
                            }
                        }
                        else if (objRelation3.ObjID1 != userData.EmployeePost ||
                            objRelation3.ObjName1 != userData.EmployeePostName ||
                            objRelation3.ObjType1 != "S" ||
                            objRelation3.ObjName2 != userData.Name)
                        {
                            objRelation3.ObjID1 = userData.EmployeePost;
                            objRelation3.ObjName1 = userData.EmployeePostName ?? "";
                            objRelation3.ObjType1 = "S";
                            objRelation3.ObjName2 = userData.Name ?? "";
                            objRelation3.SyncTime = DateTime.Now;
                            uObjRelationList.Add(objRelation3);
                        }
                    }
                }

                // 更新NIP_Sync_UserBossRelation
                if (userBossIsDel && !userData.SapEmployeeId.IsNullOrEmpty())
                {
                    if (boss != null && !boss.SapEmployeeId.IsNullOrEmpty())
                    {
                        var userBoss = new NIP_Sync_UserBossRelation
                        {
                            EmployeeID = userData.SapEmployeeId,
                            EmployeeName = userData.Name,
                            BossEmployeeID1 = boss.SapEmployeeId,
                            BossEmployeeName1 = boss.Name,
                        };                        
                        var boss2 = userBossData.FirstOrDefault(x => x.SapEmployeeId.Equals(boss.BossEmployeeId));
                        if (boss2 == null || boss2.SapEmployeeId.IsNullOrEmpty())
                        {
                            iUserBossRelation.Add(userBoss);
                            continue;
                        }
                        else
                        {
                            userBoss.BossEmployeeID2 = boss2.SapEmployeeId;
                            userBoss.BossEmployeeName2 = boss2.Name;
                        }
                        var boss3 = userBossData.FirstOrDefault(x => x.SapEmployeeId.Equals(boss2.BossEmployeeId));
                        if (boss3 == null || boss3.SapEmployeeId.IsNullOrEmpty())
                        {
                            iUserBossRelation.Add(userBoss);
                            continue;
                        }
                        else
                        {
                            userBoss.BossEmployeeID3 = boss3.SapEmployeeId;
                            userBoss.BossEmployeeName3 = boss3.Name;
                        }
                        var boss4 = userBossData.FirstOrDefault(x => x.SapEmployeeId.Equals(boss3.BossEmployeeId));
                        if (boss4 == null || boss4.SapEmployeeId.IsNullOrEmpty())
                        {
                            iUserBossRelation.Add(userBoss);
                            continue;
                        }
                        else
                        {
                            userBoss.BossEmployeeID4 = boss4.SapEmployeeId;
                            userBoss.BossEmployeeName4 = boss4.Name;
                        }
                        var boss5 = userBossData.FirstOrDefault(x => x.SapEmployeeId.Equals(boss4.BossEmployeeId));
                        if (boss5 == null || boss5.SapEmployeeId.IsNullOrEmpty())
                        {
                            iUserBossRelation.Add(userBoss);
                            continue;
                        }
                        else
                        {
                            userBoss.BossEmployeeID5 = boss5.SapEmployeeId;
                            userBoss.BossEmployeeName5 = boss5.Name;
                        }
                        var boss6 = userBossData.FirstOrDefault(x => x.SapEmployeeId.Equals(boss5.BossEmployeeId));
                        if (boss6 == null || boss6.SapEmployeeId.IsNullOrEmpty())
                        {
                            iUserBossRelation.Add(userBoss);
                            continue;
                        }
                        else
                        {
                            userBoss.BossEmployeeID6 = boss6.SapEmployeeId;
                            userBoss.BossEmployeeName6 = boss6.Name;
                        }
                        var boss7 = userBossData.FirstOrDefault(x => x.SapEmployeeId.Equals(boss6.BossEmployeeId));
                        if (boss7 == null || boss7.SapEmployeeId.IsNullOrEmpty())
                        {
                            iUserBossRelation.Add(userBoss);
                            continue;
                        }
                        else
                        {
                            userBoss.BossEmployeeID7 = boss7.SapEmployeeId;
                            userBoss.BossEmployeeName7 = boss7.Name;
                        }
                        var boss8 = userBossData.FirstOrDefault(x => x.SapEmployeeId.Equals(boss7.BossEmployeeId));
                        if (boss8 == null || boss8.SapEmployeeId.IsNullOrEmpty())
                        {
                            iUserBossRelation.Add(userBoss);
                            continue;
                        }
                        else
                        {
                            userBoss.BossEmployeeID8 = boss8.SapEmployeeId;
                            userBoss.BossEmployeeName8 = boss8.Name;
                        }
                        var boss9 = userBossData.FirstOrDefault(x => x.SapEmployeeId.Equals(boss7.BossEmployeeId));
                        if (boss9 == null || boss9.SapEmployeeId.IsNullOrEmpty())
                        {
                            iUserBossRelation.Add(userBoss);
                            continue;
                        }
                        else
                        {
                            userBoss.BossEmployeeID9 = boss9.SapEmployeeId;
                            userBoss.BossEmployeeName9 = boss9.Name;
                        }
                    }
                    else
                    {
                        var userBoss = new NIP_Sync_UserBossRelation
                        {
                            EmployeeID = userData.SapEmployeeId,
                            EmployeeName = userData.Name,
                        };
                        iUserBossRelation.Add(userBoss);
                    }
                }
            }

            try
            {
                await _dbNIPWorkFlow.Fastest<MDS_Hr_Person>().BulkCopyAsync(iHrPersonList);
                await _dbNIPWorkFlow.Fastest<MDS_Hr_Person>().BulkUpdateAsync(uHrPersonList);
            }
            catch(Exception ex)
            {
                _logger.Error($"更新MDS_Hr_Person：{ex.Message}");
            }

            try
            {
                await _dbNIPWorkFlow.Fastest<MDS_Hr_Post>().BulkCopyAsync(iHrPostList);
                await _dbNIPWorkFlow.Fastest<MDS_Hr_Post>().BulkUpdateAsync(uHrPostList);
            }
            catch (Exception ex)
            {
                _logger.Error($"更新MDS_Hr_Post：{ex.Message}");
            }

            try
            {
                await _dbNIPWorkFlow.Fastest<MDS_User>().BulkCopyAsync(iUserList);
                await _dbNIPWorkFlow.Fastest<MDS_User>().BulkUpdateAsync(uUserList);
            }
            catch (Exception ex)
            {
                _logger.Error($"更新MDS_User：{ex.Message}");
            }

            try
            {
                await _dbNIPWorkFlow.Fastest<MDS_Hr_UserOrgRelation>().BulkCopyAsync(iUserOrgList);
                await _dbNIPWorkFlow.Fastest<MDS_Hr_UserOrgRelation>().BulkUpdateAsync(uUserOrgList);
            }
            catch (Exception ex)
            {
                _logger.Error($"更新MDS_Hr_UserOrgRelation：{ex.Message}");
            }

            try
            {
                await _dbNIPWorkFlow.Fastest<MDS_Hr_ObjRelation>().BulkCopyAsync(iObjRelationList);
                await _dbNIPWorkFlow.Fastest<MDS_Hr_ObjRelation>().BulkUpdateAsync(uObjRelationList);
            }
            catch (Exception ex)
            {
                _logger.Error($"更新MDS_Hr_ObjRelation：{ex.Message}");
            }

            try
            {
                await _dbNIPWorkFlow.Fastest<NIP_Sync_UserBossRelation>().BulkCopyAsync(iUserBossRelation);
            }
            catch (Exception ex)
            {
                _logger.Error($"更新NIP_Sync_UserBossRelation：{ex.Message}");
            }

            await DeleteLeaveUserOrgRelation(nipUserInfo, userOrgs);

            await SyncBossRelation(nipUserInfo);

            watch.Stop();
            _logger.Information("OldBPMSyncUserJob.SyncUser，消耗时间：" + watch.Elapsed.TotalSeconds);
        }

        /// <summary>
        /// 获取立邦数据库所有用户数据
        /// </summary>
        /// <returns></returns>
        private async Task<List<V_USERINFO_ALL>> GetNIPVUserInfo()
        {
            var query = await _dbNIPWorkFlow.Ado.SqlQueryAsync<V_USERINFO_ALL>(
                "select * from lnk_uupm.uupm.dbo.V_USERINFO_ALL WHERE SapEmployeeId LIKE '000%' AND LEN(SapEmployeeId) = 8");
            query.ForEach(x =>
            {
                x.SapEmployeeId = x.SapEmployeeId?.Trim();
                x.Name = x.Name?.Replace(" ", "");
                x.LoginName = x.LoginName?.Trim();
                x.Email = x.Email?.Trim();
                x.EmployeePost = x.EmployeePost?.Trim();
                x.EmployeePostName = x.EmployeePostName?.Trim();
                x.SapCompanyCode = x.SapCompanyCode?.Trim();
                x.SapCompanyName = x.SapCompanyName?.Trim();
                x.Org = x.Org?.Trim();
                x.BossEmployeeId = x.BossEmployeeId?.Trim();
                x.BossName = x.BossName?.Replace(" ", "");
                x.BossEmployeePost = x.BossEmployeePost?.Trim();
            });
            return query;
        }

        /// <summary>
        /// 获取立邦数据库所有组织数据
        /// </summary>
        /// <returns></returns>
        private async Task<List<Nippon_Org_Relation>> GetNIPOrgRelation()
        {
            var query = await _dbNIPWorkFlow.Ado.SqlQueryAsync<Nippon_Org_Relation>(
                "SELECT * FROM lnk_uupm.uupm.dbo.Nippon_Org_Relation");
            return query;
        }

        /// <summary>
        /// 更新表MDS_Hr_Organization
        /// </summary>
        /// <param name="orgRelations"></param>
        private async Task SyncMdsHrOrganization(List<Nippon_Org_Relation> orgRelations)
        {
            try
            {
                var result = await _dbNIPWorkFlow.Deleteable<MDS_Hr_Organization>()
                    .Where(x => x.LevelID != "10" && x.LevelID != "20").ExecuteCommandAsync();
                if (result > 0 || !await _dbNIPWorkFlow.Queryable<MDS_Hr_Organization>().AnyAsync(x => x.LevelID != "10" && x.LevelID != "20"))
                {
                    var iList = new List<MDS_Hr_Organization>();
                    foreach (var orgRelation in orgRelations)
                    {
                        var levelId = "";
                        var levelName = "";
                        switch (orgRelation.SOBID)
                        {
                            case "99000000":
                                levelId = "30";
                                levelName = "项目";
                                break;
                            case "50076763":
                                levelId = "40";
                                levelName = "组织";
                                break;
                            case "50077099":
                                levelId = "40";
                                levelName = "组织";
                                break;
                            case "50077245":
                                levelId = "40";
                                levelName = "组织";
                                break;
                            default:
                                levelId = "50";
                                levelName = "部门";
                                break;
                        }
                        var entity = new MDS_Hr_Organization
                        {
                            ObjType = "O",
                            ObjID = orgRelation.OBJID,
                            ObjName = orgRelation.STEXT,
                            LevelID = levelId,
                            LevelName = levelName,
                            IsSync = true,
                            SyncTime = DateTime.Now,
                        };
                        iList.Add(entity);
                    }
                    await _dbNIPWorkFlow.Fastest<MDS_Hr_Organization>().BulkCopyAsync(iList);
                }
            }
            catch(Exception ex)
            {
                _logger.Error($"SyncMdsHrOrganization Error：{ex.Message}");
            }
        }

        /// <summary>
        /// 更新表MDS_Hr_ObjRelation
        /// </summary>
        /// <param name="orgRelations"></param>
        private async Task SyncMDSHrObjRelation(List<Nippon_Org_Relation> orgRelations)
        {
            try
            {
                var result = await _dbNIPWorkFlow.Deleteable<MDS_Hr_ObjRelation>()
                    .Where(x => x.RelationType.Equals("A002") && x.ObjType1.Equals("O") && x.ObjType2.Equals("O")).ExecuteCommandAsync();
                if (result > 0 ||
                    !await _dbNIPWorkFlow.Queryable<MDS_Hr_ObjRelation>()
                    .AnyAsync(x => x.RelationType.Equals("A002") && x.ObjType1.Equals("O") && x.ObjType2.Equals("O")))
                {
                    var iList = new List<MDS_Hr_ObjRelation>();
                    foreach (var orgRelation in orgRelations)
                    {
                        var sobOrg = orgRelations.FirstOrDefault(x => x.OBJID.Equals(orgRelation.SOBID));
                        var entity = new MDS_Hr_ObjRelation
                        {
                            ObjType1 = "O",
                            ObjID1 = orgRelation.OBJID,
                            ObjName1 = orgRelation.STEXT,
                            RelationType = "A002",
                            ObjType2 = "O",
                            ObjID2 = orgRelation.SOBID.Equals("99000000") ? "10000000" : orgRelation.SOBID,
                            ObjName2 = orgRelation.SOBID.Equals("99000000") ? "立邦" : sobOrg?.STEXT ?? "",
                            SyncTime = DateTime.Now,
                            IsSync = true,
                            Deleted = false,
                        };
                        iList.Add(entity);
                    }
                    await _dbNIPWorkFlow.Fastest<MDS_Hr_ObjRelation>().BulkCopyAsync(iList);
                }
            }
            catch(Exception ex)
            {
                _logger.Error($"SyncMDSHrObjRelation A002 Error：{ex.Message}");
            }
        }

        /// <summary>
        /// 删除离职人员的组织结构数据
        /// </summary>
        /// <param name="delUserOrgs"></param>
        private async Task DeleteLeaveUserOrgRelation(List<V_USERINFO_ALL> nipUserInfo, List<MDS_Hr_UserOrgRelation> userOrgs)
        {
            try
            {
                var delUserOrgs = from x in userOrgs
                                  join u in nipUserInfo.Where(q => q.Status.Equals("0"))//离职数据
                                  on x.EmployeeID.Trim() equals u.SapEmployeeId
                                  where x.OBJID1 != null
                                  select x;
                var uList = new List<MDS_Hr_UserOrgRelation>();
                foreach (var delUserOrg in delUserOrgs)
                {
                    delUserOrg.OBJID0 = null;
                    delUserOrg.STEXT0 = null;
                    delUserOrg.OBJID1 = null;
                    delUserOrg.STEXT1 = null;
                    delUserOrg.SHORT1 = null;
                    delUserOrg.SOBID1 = null;
                    delUserOrg.OBJID2 = null;
                    delUserOrg.STEXT2 = null;
                    delUserOrg.SHORT2 = null;
                    delUserOrg.SOBID2 = null;
                    delUserOrg.OBJID3 = null;
                    delUserOrg.STEXT3 = null;
                    delUserOrg.SHORT3 = null;
                    delUserOrg.SOBID3 = null;
                    delUserOrg.OBJID4 = null;
                    delUserOrg.STEXT4 = null;
                    delUserOrg.SHORT4 = null;
                    delUserOrg.SOBID4 = null;
                    delUserOrg.OBJID5 = null;
                    delUserOrg.STEXT5 = null;
                    delUserOrg.SHORT5 = null;
                    delUserOrg.SOBID5 = null;
                    delUserOrg.OBJID6 = null;
                    delUserOrg.STEXT6 = null;
                    delUserOrg.SHORT6 = null;
                    delUserOrg.SOBID6 = null;
                    delUserOrg.OBJID7 = null;
                    delUserOrg.STEXT7 = null;
                    delUserOrg.SHORT7 = null;
                    delUserOrg.SOBID7 = null;
                    delUserOrg.OBJID8 = null;
                    delUserOrg.STEXT8 = null;
                    delUserOrg.SHORT8 = null;
                    delUserOrg.SOBID8 = null;
                    delUserOrg.OBJID9 = null;
                    delUserOrg.STEXT9 = null;
                    delUserOrg.SHORT9 = null;
                    delUserOrg.SOBID9 = null;
                    delUserOrg.OBJID10 = null;
                    delUserOrg.STEXT10 = null;
                    delUserOrg.SHORT10 = null;
                    delUserOrg.SOBID10 = null;
                    uList.Add(delUserOrg);
                }
                await _dbNIPWorkFlow.Fastest<MDS_Hr_UserOrgRelation>().BulkUpdateAsync(uList);
            }
            catch(Exception ex)
            {
                _logger.Error($"DeleteLeaveUserOrgRelation Error：{ex.Message}");
            }
        }

        /// <summary>
        /// 同步省市数据
        /// </summary>
        /// <returns></returns>
        private async Task SyncAllSite()
        {
            try
            {
                var sites = await _dbNIPWorkFlow.Ado.SqlQueryAsync<Sites>(
                    @"SELECT Province,CityName FROM lnk_uupm.uupm.dbo.V_USERINFO_ALL WHERE ID IN
                    (SELECT t.ID FROM (
                    SELECT ROW_NUMBER() OVER (PARTITION BY CityName,Province ORDER BY ID DESC) AS keyId2,* 
                    FROM lnk_uupm.uupm.dbo.V_USERINFO_ALL)T
                    WHERE t.KeyId2=1 AND ISNULL(CityName,'')<>'')");
                var result = await _dbNIPWorkFlow.Deleteable<NIP_BPM_Site>().ExecuteCommandAsync();
                if (result > 0 || !await _dbNIPWorkFlow.Queryable<NIP_BPM_Site>().AnyAsync())
                {
                    var iList = new List<NIP_BPM_Site>();
                    foreach (var site in sites)
                    {
                        iList.Add(new NIP_BPM_Site
                        {
                            Province = site.Province,
                            CityName = site.CityName,
                        });
                    }
                    await _dbNIPWorkFlow.Fastest<NIP_BPM_Site>().BulkCopyAsync(iList);
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"SyncAllSite Error：{ex.Message}");
            }
        }

        /// <summary>
        /// 步Sync_PC_USER_T用户表数据，全量同步，包括离职数据
        /// </summary>
        /// <param name="nipUserInfo"></param>
        /// <returns></returns>
        private async Task SyncPCUSERT(List<V_USERINFO_ALL> nipUserInfo)
        {
            try
            {
                var users = nipUserInfo.GroupBy(x => x.Id).Select(x => x.FirstOrDefault()).ToList();
                var result = await _dbNIPWorkFlow.Deleteable<NIP_Sync_PC_USER_T>().ExecuteCommandAsync();
                if (result > 0 || !await _dbNIPWorkFlow.Queryable<NIP_Sync_PC_USER_T>().AnyAsync())
                {
                    var iList = new List<NIP_Sync_PC_USER_T>();
                    foreach (var user in users)
                    {
                        iList.Add(new NIP_Sync_PC_USER_T
                        {
                            Id = user.Id,
                            Name = user.Name,
                            LoginName = user.LoginName,
                            Password = "123456",
                            InUse = "1",
                            Email = user.Email,
                            LastLoginTime = "1900-01-01 00:00:00".ObjToDate(),
                            Mobile = user.Mobile,
                            IdCard = null,
                            ValidDate = user.ContractBegin == null ? "1900-01-01 00:00:00".ObjToDate() : user.ContractBegin,
                            UserType = 1,
                            SapEmployeeId = user.SapEmployeeId,
                            SapPostId = user.EmployeePost.ObjToNullInt(),
                            SapPostName = user.EmployeePostName,
                            SapCostCenterCode = user.SapCostCenterCode,
                            SapCostCenter = user.SapCostCenter,
                            SapCompanyCode = user.SapCompanyCode,
                            SapCompanyName = user.SapCompanyName,
                            Status = user.Status,
                            Province = user.Province,
                            CityName = user.cityname,
                            ABKRS = user.ABKRS,
                        });
                    }
                    await _dbNIPWorkFlow.Fastest<NIP_Sync_PC_USER_T>().BulkCopyAsync(iList);
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"SyncPCUSERT Error：{ex.Message}");
            }
        }

        /// <summary>
        /// 同步表NIP_Sync_Boss_Relation，全量同步
        /// </summary>
        /// <param name="nipUserInfo"></param>
        /// <returns></returns>
        private async Task SyncBossRelation(List<V_USERINFO_ALL> nipUserInfo)
        {
            try
            {
                var users = nipUserInfo.GroupBy(x => x.Id).Select(x => x.FirstOrDefault()).ToList();
                var result = await _dbNIPWorkFlow.Deleteable<NIP_Sync_Boss_Relation>().ExecuteCommandAsync();
                if (result > 0 || !await _dbNIPWorkFlow.Queryable<NIP_Sync_Boss_Relation>().AnyAsync())
                {
                    var iList = new List<NIP_Sync_Boss_Relation>();
                    foreach (var user in users)
                    {
                        iList.Add(new NIP_Sync_Boss_Relation
                        {
                            EmployeeId = user.SapEmployeeId,
                            EmployeeName = user.Name,
                            Contract = user.Contract,
                            ContractName = user.ContractName,
                            ContractBegin = user.ContractBegin,
                            Duty = user.Duty.ObjToNullInt(),
                            DutyName = user.DutyName,
                            Org = user.Org.ObjToNullInt(),
                            OrgName = user.OrgName,
                            EmployeePost = user.EmployeePost.ObjToNullInt(),
                            EmployeePostName = user.EmployeePostName,
                            POSTY = user.POSTY,
                            POSTE = user.POSTE,
                            POSNC = user.POSNC,
                            BossEmployeeId = user.BossEmployeeId,
                            BossName = user.BossName,
                            BossEmployeePost = user.BossEmployeePost,
                            Sex = user.SEX.ObjToNullInt(),
                            Province = user.Province,
                            CityName = user.cityname,
                            ABKRS = user.ABKRS,
                        });
                    }
                    await _dbNIPWorkFlow.Fastest<NIP_Sync_Boss_Relation>().BulkCopyAsync(iList);
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"SyncBossRelation Error：{ex.Message}");
            }
        }
    }
}
